package com.grades.springboot.service.impl;


import com.grades.springboot.entity.Result;
import com.grades.springboot.service.CaptchaService;
import com.wf.captcha.GifCaptcha;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Service
public class CaptchaServiceImpl implements CaptchaService {
    @Override
    public Result<?> getCaptcha(HttpServletRequest request, HttpServletResponse response) {
        GifCaptcha gifCaptcha = new GifCaptcha(130, 38, 4);
        // 输出验证码图片
//        CaptchaUtil.out(gifCaptcha, request, response);
        // 获取验证码文本
        String verCode = gifCaptcha.text().toLowerCase();
        // 将验证码文本保存到session中
        request.getSession().setAttribute("CAPTCHA", verCode);
        //生成base64编码并返回
        return Result.success(gifCaptcha.toBase64());
    }

    @Override
    public Boolean checkCaptcha(String code, HttpServletRequest request) {
        String sessionCode = request.getSession().getAttribute("CAPTCHA").toString();
        return code.equals(sessionCode);
//        if (sessionCode == null) {
//            return Result.error("验证码为空");
//        }
//        if (!code.equals(sessionCode)) {
//            return Result.error("验证码错误");
//        }
    }
}
